<template>
  <div class="announcement-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>公告管理</span>
          <el-button type="primary" @click="showAddDialog">发布公告</el-button>
        </div>
      </template>

      <el-table :data="announcements" style="width: 100%">
        <el-table-column prop="title" label="标题" min-width="200"/>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === '通知' ? 'primary' : 'warning'">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="发布人" width="100"/>
        <el-table-column prop="time" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteAnnouncement(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加公告对话框 -->
    <el-dialog v-model="addDialogVisible" title="发布公告" width="70%">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="addForm.title"/>
        </el-form-item>

        <el-form-item label="公告类型" prop="type">
          <el-radio-group v-model="addForm.type">
            <el-radio label="通知">通知</el-radio>
            <el-radio label="公告">公告</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="公告内容" prop="content">
          <el-input
              v-model="addForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入公告内容"
          />
        </el-form-item>

        <el-form-item label="发布人" prop="author">
          <el-input v-model="addForm.author"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAnnouncement" :loading="submitting">
          发布
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '../../utils/request'

const announcements = ref([])
const addDialogVisible = ref(false)
const addFormRef = ref()
const submitting = ref(false)

const addForm = reactive({
  title: '',
  type: '通知',
  content: '',
  author: ''
})

const addRules = {
  title: [{required: true, message: '请输入公告标题', trigger: 'blur'}],
  type: [{required: true, message: '请选择公告类型', trigger: 'change'}],
  content: [{required: true, message: '请输入公告内容', trigger: 'blur'}],
  author: [{required: true, message: '请输入发布人', trigger: 'blur'}]
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

const loadAnnouncements = async () => {
  try {
    const response = await request.get('/api/board/list')
    if (response.data.code === 200) {
      announcements.value = response.data.data
    }
  } catch (error) {
    console.error('加载公告数据失败:', error)
  }
}

const showAddDialog = () => {
  addForm.title = ''
  addForm.type = '通知'
  addForm.content = ''
  addForm.author = ''
  addDialogVisible.value = true
}

const submitAnnouncement = async () => {
  if (!addFormRef.value) return

  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const response = await request.post('/api/board/add', addForm)
        if (response.data.code === 200) {
          ElMessage.success('发布成功')
          addDialogVisible.value = false
          await loadAnnouncements()
        }
      } catch (error) {
        ElMessage.error('发布失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const deleteAnnouncement = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条公告吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })


    const response = await request.delete(`/api/board/delete/${row.id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      await loadAnnouncements()
    }

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadAnnouncements()
})
</script>

<style scoped>
.announcement-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
